package ms.unicorn.language.languagedef;

import ms.unicorn.EPhantomAttribute;
import ms.unicorn.Element;
import ms.unicorn.modellanguage.LanguageElement;
import ms.unicorn.ui.figures.ConnectionFigure;
import ms.unicorn.ui.figures.EntityPlateFigure;

import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.emf.common.util.EList;
import org.eclipse.gef.EditPart;
import org.eclipse.gmf.runtime.draw2d.ui.figures.PolylineConnectionEx;
import org.eclipse.xtext.xbase.interpreter.impl.XbaseInterpreter;

@SuppressWarnings("restriction")
public class ElementDefUtil {

	public static FigureContainer createFigure(LanguageElement element, ElementDef def, EditPart editpart) {
		
		Class<?> defaultFigImplClass = (def instanceof EntityDef) ? EntityPlateFigure.class : ConnectionFigure.class;
		
		FigureDef figDef = LanguageDefUtil.resolveDefinition(def.getFigure());
		FigureContainer figures = FigureDefUtil.resolveFigure(element, figDef, def.getFigureParams(), editpart, defaultFigImplClass);
		IFigure fig = figures.getMainFigure();
		
		EList<Parameter> list = def.getFigureParams();
		Dimension size = ParameterUtil.getSize(list, null);
		if (size != null) 
			fig.setSize(size);
		
		return figures;
	}
	
	public static boolean isResizeableFigure(ElementDef def) {
		return ParameterUtil.getParameter(def.getFigureParams(), ParameterType.RESIZABLE, true);
	}

	public static void initialize(LanguageElement langE, Element element) {
		XbaseUtil.context = langE.getLanguage().getContext();
		XbaseUtil.interpreter = (XbaseInterpreter) langE.getLanguage().getInterpreter();
		
		ElementDef def = langE.getDefinition();
		
		TagDef fields = TagDefUtil.getFields(def);
		if (fields != null)
			for (TagEntryDef field: fields.getEntry()) 
				if (field.getValue() != null) {
					Object value = XbaseUtil.evaluate(field.getValue(), null);
					EPhantomAttribute attr = (EPhantomAttribute) TagDefUtil.getEAttribute(field);
					if (attr != null) attr.setValue(element, value);
				}
	}
}
